<?php

namespace App\Http\Controllers\Web\Member\Buyer;

use App\Http\Controllers\Web\BaseController;
use Illuminate\Http\Request;
use Exception;
use tech\core\Util;
use tech\core\eSign;


include(app_path() ."/Library/API/eSignOpenAPI.php");

class EQBaoController extends BaseController
{
    protected $api_url = [
        'index' => ['get', 'eqbao'],
        'show' => ['get', 'eqbao/%d'],
        'store' => ['post', 'eqbao'],
        'update' => ['put', 'eqbao/%d'],
        'find_by_userid'=>['get','eqbao/find_by_userid'],
        
        'contract_index' => ['get', 'eqbao/contract'],
        'contract_show' => ['get', 'eqbao/contract/%d'],
        'contract_store' => ['post', 'eqbao/contract'],
        'contract_update' => ['put', 'eqbao/contract/%d'],
        'find_by_orderid'=>['get','eqbao/contract/find_by_orderid/%d'],
        
        'company_info'=>['get','seller/companymaterial/%d/showusercompany'],
        
        'order_show'  => ['get',  'seller/service/orders/%d'],
        
        'contract_mb_index' => ['get', 'seller/contracts'],
    ];
    
 
    protected $request;
    
    protected $sign;

    public function __construct(Request $request)
    {
        $this->request = $request;
        
        //实例化
        try {
            $this->sign = new eSign();
        } catch (Exception $e) {
            echo $e->getMessage();
            exit;
        }
    }

    
    public function index(){
        $pdf = new \TCPDF();
        // 设置文档信息
        $pdf->SetCreator('服务合同');
        $pdf->SetAuthor('e#在线');
        $pdf->SetTitle('服务合同');
        $pdf->SetSubject('服务合同');
        $pdf->SetKeywords('TCPDF, PDF, PHP');
        //$pdf->setPrintHeader(false);
        
        // 设置页眉和页脚信息
        //$pdf->SetHeaderData('tcpdf_logo.jpg', 30, 'LanRenKaiFA.com', '合同文件！', [0, 64, 255], [0, 64, 128]);
        $pdf->SetHeaderData('', 130, '', '合同编号：201806250012', [], [255,255,255]);
        $pdf->setFooterData([0, 64, 0], [0, 64, 128]);
        
        // 设置页眉和页脚字体
        $pdf->setHeaderFont(['stsongstdlight', '', '12']);
        $pdf->setFooterFont(['helvetica', '', '8']);
        
        // 设置默认等宽字体
        $pdf->SetDefaultMonospacedFont('courier');
        
        // 设置间距
        $pdf->SetMargins(15, 15, 15);//页面间隔
        $pdf->SetHeaderMargin(5);//页眉top间隔
        $pdf->SetFooterMargin(10);//页脚bottom间隔
        
        // 设置分页
        $pdf->SetAutoPageBreak(true, 25);
        
        // set default font subsetting mode
        $pdf->setFontSubsetting(true);
        
        //设置字体 stsongstdlight支持中文
        $pdf->SetFont('stsongstdlight', '', 14);
        
        //第一页
        $pdf->AddPage();
        $pdf->writeHTML('<div style="text-align: center"><h1>资质合同</h1></div>');
        $pdf->writeHTML('<p>委托方（甲方）：（借资质方）</p>');
        $pdf->writeHTML('<p style="color: red">受托方（乙方）：(资质提供方)</p>');
        $pdf->Ln(5);//换行符
        $pdf->writeHTML(' ');
        
        $pdf->writeHTML(' </p>');
        
        //第二页
        //$pdf->AddPage();
        //$pdf->writeHTML('<h1>更多内容</h1>');
        
        //输出PDF
        //$pdf->Output(public_path("uploads").DIRECTORY_SEPARATOR.  't.pdf', 'F');//I输出、D下载
        
        $data['step'] = $this->request->get("step","");
        return view('web.eqbao', $data);
    }
    
    /**
     * 初始化和登录
     */
    
    public function init()
    {
        $iRet = $this->sign->init();
        if (0 === $iRet) {
            $array = array(
                "errCode" => 0,
                "msg" => "初始化成功",
                "errShow" => true
            );
            $this->response($array);
        }
    }
    
    /**
     * 添加个人用户
     */
    public function addPerson()
    {
        $mobile = $this->request->post('mobile','');
        $name = $this->request->post('name','');
        $idNo = $this->request->post('id',''); 
        $personarea =  $this->request->post('area'); 
        $email =  $this->request->post('email','');
        $organ =  $this->request->post('organ','');
        $title =  $this->request->post('title','');
        $address = $this->request->post('address','');
        
        $ret = $this->sign->addPersonAccount(
            $mobile,
            $name,
            $idNo,
            $personarea,
            $email,
            $organ,
            $title,
            $address
            );
        
        $this->response($ret);
    }
    
    //合同授权
    public function contract_auth(){
        $result = http_web($this->api_url['find_by_userid'])->send();
        $data = [];
        if(isset($result['data'][0])){
            return redirect()->route('contracts.index');
        }
      
        $info = http_web($this->api_url['company_info'],[session('user_id')])->send();
        $data['company_name']  = "";
        $data['company_address']  = "";
        
        if(isset($info['data']['data']['company'])){
            $company = $info['data']['data']['company'];
            $data['company_name'] = $company['company_name'];
            $data['company_address'] = $company['company_address'];
        }
        
        
        $data['mobile']=session('user_phone');
   
        return view('web.user.seller.contract_admittance',$data);
    }
    
    /**
     * 添加企业用户
     */
    public function addOrganize()
    {
        
        $params = $this->request->all(['mobile', 'name', 'organCode', 'regType', 'email', 'organType', 'legalArea', 'userType', 'agentName', 'agentIdNo', 'legalName', 'legalIdNo','auth_card','company_address']);
        $ret = $this->sign->addOrganizeAccount(
            $params['mobile'],
            $params['name'],
            $params['organCode'],
            1,//$params['regType'] ,
            $params['email'],
            0,//$params['organType'],
            0,//$params['legalArea'] ,
            $params['userType'] ,
            $params['agentName'] ,
            $params['agentIdNo'] ,
            $params['agentName'],//$params['legalName'],对的相同赋值参数
            $params['agentIdNo'] ,//$params['legalIdNo'],对的相同赋值参数
            $address = '',
            $scope = '');
        
        $resp = ['status'=>0,'msg'=>$ret['msg']];
        if(isset($ret['accountId'])){
            $data['account_id'] = $ret['accountId'];
            $data['organ_code'] = $params['organCode'];
            $data['user_type'] = $params['userType'];
            $data['auth_name'] = $params['agentName'];
            $data['user_name'] = session("user_name");
            $data['auth_card'] = $params['agentIdNo'];
            $data['company_address'] = $params['company_address'];
            $data['company_name'] = $params['name'];
            
            $ret = $this->sign->addTemplateSeal(
                $ret['accountId'],
                'star',
                'red',
                '合同专用章',
                ''
                );
            if(isset($ret['imageBase64'])){
                $data['yz_data'] = $ret['imageBase64'];
            }
            
            $info = http_web($this->api_url['store'])->send($data);
            if(isset($info['code']) && $info['code'] == 0){
                $resp['status'] = 1;
                $resp['msg'] = $ret['msg'];
            }
        } 
        
        $this->response($resp);
    }
    
    public function contract_msg(){
        $data = [];
        $info = http_web($this->api_url['company_info'],[session('user_id')])->send();
        if(isset($info['data']['data']['company'])){
            $company = $info['data']['data']['company'];
            $data['company'] = $company;
        }
        
        return view('web.user.seller.contract_msg',$data);
    }
    
    public function contract_write(){
        $order_id = $this->request->get("order_id",0);
        $base_info['name']=$this->request->get("name","");
        $base_info['phone']=$this->request->get("phone","");
        $base_info['term']=$this->request->get("term","");
        $base_info['bond']=$this->request->get("bond","");
        
        $base_info = json_encode($base_info);
        
        $data = [];
        $params = [
            'orderBy' => 'updated_at',
            'sortedBy' => 'desc',
            'page'=>$this->request->get('page',1)
        ];
        $ret  = http_web($this->api_url['contract_mb_index'])->send($params);
        if(isset($ret['data']['list'])){
            $data['contracts'] = $ret['data']['list'];
        }
     
      
        $ret = http_web($this->api_url['order_show'], [$order_id])->send($params);
        
        $order_code = "";
        if(isset($ret['data']['user_id']) && $ret['data']['user_id']){
            $order_code = $ret['data']['order_code'];
            $info = http_web($this->api_url['company_info'],[$ret['data']['user_id']])->send();
            if(isset($info['data']['data']['company'])){
                $company = $info['data']['data']['company'];
                $data['buyer_company'] = $company;
            }
        }
 
        $info = http_web($this->api_url['company_info'],[session('user_id')])->send();
      
        if(isset($info['data']['data']['company'])){
            $company = $info['data']['data']['company'];
            $data['seller_company'] = $company;
        }
      
        $data['contract_code'] = 'HT'.substr($order_code,5).rand(10,100);
        $data['base_info']=$base_info;
        $data['order_id']=$order_id;
        
        return view('web.user.seller.contract_write',$data);
    }
    
    public function contract_post(){
        $data['order_id'] = $this->request->post('order_id','');
        $data['seller_user_id'] = session('user_id');
        $data['seller_sign_id'] = 'd';
        $data['status'] = 0;
        $data['contract_content'] = $this->request->post('content','');
        $data['base_info'] = $this->request->post('base_info','');
        $data['contract_code'] = $this->request->post('contract_code','');
        $data['buyer_name']=$this->request->post('buyer_name','');
        $data['seller_name']=$this->request->post('seller_name','');
        $order_id=$data['order_id'];
        $file_url = public_path("uploads").DIRECTORY_SEPARATOR.  $data['contract_code'].'.pdf';
        //
        $pdf = new \TCPDF();
        $pdf->SetCreator('资质合同');
        $pdf->SetAuthor('e#在线');
        $pdf->SetTitle('资质合同');
        $pdf->SetSubject('资质合同');
        $pdf->SetKeywords('TCPDF, PDF, PHP');
        $pdf->setPrintHeader(false);
        $pdf->setFooterData([0, 64, 0], [0, 64, 128]);
        $pdf->setFooterFont(['helvetica', '', '8']);
        $pdf->SetDefaultMonospacedFont('courier');
        $pdf->SetMargins(15, 15, 15);//页面间隔
        $pdf->SetHeaderMargin(5);//页眉top间隔
        $pdf->SetFooterMargin(10);//页脚bottom间隔
        $pdf->SetAutoPageBreak(true, 25);
        $pdf->setFontSubsetting(true);
        $pdf->SetFont('stsongstdlight', '', 10);
        
        //$pdf->SetFontSize(6);
        $pdf->AddPage();
        $pdf->writeHTML('<body style="width:100%;">');
        $pdf->writeHTML('<p>合同编号：'.$data['contract_code'].'</p>');
        $pdf->Ln(2); 
        $pdf->writeHTML('<p >甲方：'.$data['buyer_name'].'</p>');
        $pdf->Ln(2); 
        $pdf->writeHTML('<p >乙方：'.$data['seller_name'].'</p>');
        $pdf->Ln(2); 
        $pdf->writeHTML('<p >根据《中华人民共和国合同法》及相关法律法规的规定，甲乙双方在平等、自愿、公平、协商一致的基础上，就甲方委托乙方提供服务的有关事宜达成如下协议：</p>');
        $pdf->Ln(2); 
        $pdf->writeHTML('<p >合同条例：</p>');
        $pdf->Ln(2); 
        
        $pdf->writeHTML('<p>'.$data['contract_content'].'</p>');
        $pdf->Ln(2); 
        $pdf->writeHTML('<p><table style="width: 100%;">
            <tr>
                <td >甲方：'.$data['buyer_name'].'</td>
                <td style="text-align: right;">乙方：'.$data['seller_name'].'</td>
            </tr>
        </table></p>');
        $pdf->writeHTML('</body>');
        $pdf->Output($file_url, 'F');//I输出、D下载
        
        $data['file_url']= $file_url;
        $data['web_url'] = asset('uploads/'.$data['contract_code'].'.pdf');
        
        //
        //
        $resp = ['status'=>0,'msg'=>""];
        $user_type = $this->request->get("user_type",1);//1seller 2 buyer
       
        
        $result = http_web($this->api_url['find_by_userid'])->send();
        
        $accountId = "";
        $sealData = "";
        if(isset($result['data']['0']['account_id'])){
            $accountId = $result['data'][0]['account_id'];
            $sealData = $result['data'][0]['yz_data'];
            
            if(!$sealData){
                $resp['msg'] = "请先创建印章";
                $this->response($resp);
            }
        }else{
            $resp['msg'] = "请先创建账户";
            $this->response($resp);
        }
        
        
        $id = 0;
        
        $result = http_web($this->api_url['find_by_orderid'],[$order_id])->send();
        if(isset($result['data'][0]['id'])){
            if($user_type == 1){
                $resp['msg'] = '卖家已签署合同';
                $this->response($resp);
            }
            $id = $result['data'][0]['id'];
            if($result['data'][0]['file_url'] ){
                $file_url=$result['data'][0]['file_url'];
            }
            
            if($result['data'][0]['status'] == 1){
                $resp['msg'] = '买家已签署合同';
                $this->response($resp);
            }
        }else{
            if($user_type == 2){
                $resp['msg'] = '卖家还未签署合同';
                $this->response($resp);
            }
        }
        
        if(!$file_url){
            $resp['msg'] = '待签署文件不能为空';
            $this->response($resp);
        }
        
        $srcPdfFile=$file_url;
    
        $filename = pathinfo($srcPdfFile,PATHINFO_FILENAME);
        $dist_filename = "";
        if($filename){
            $dist_filename = 'uploads/'.$filename.'_dist.pdf';
            $dstPdfFile=public_path($dist_filename);
        }
        
        
        
        $signType = 'Single';
        $isQrcodeSign = $this->request->post('isQrcodeSign','');
        $signPos = array(
            'posPage' =>  -1,//$this->request->post('posPage',1),
            'posX' =>  400,
            'posY' =>  100,
            'key' =>   '',
            'width' => 0,
            'isQrcodeSign'  =>  false,
            'addSignTime'=>true,
        );
        $signFile = array(
            'srcPdfFile' => $srcPdfFile,
            'dstPdfFile' => $dstPdfFile,
            'fileName' =>  '',
            'ownerPassword' => ''
        );
        
        $ret = $this->sign->userSignPDF($accountId, $signFile, $signPos, $signType, $sealData, $stream = true);
        
        if(isset($ret['signServiceId'])){
            $data['file_url'] = $dist_filename;
            $data['web_url'] = asset($dist_filename);
            
            if($user_type == 1){
                $data['order_id'] = $order_id;
                $data['seller_user_id'] = session('user_id');
                $data['seller_sign_id'] = $ret['signServiceId'];
                $data['status'] = 0;
                $info = http_web($this->api_url['contract_store'])->send($data);
            }
            
            if($user_type == 2){
                $data['buyer_user_id'] = session('user_id');
                $data['buyer_sign_id'] = $ret['signServiceId'];
                $data['status'] = 1;
                $info = http_web($this->api_url['contract_update'],[$id])->send($data);
            }
            
            if(isset($info['code']) && $info['code'] == 0){
                $resp['status'] = 1;
                $resp['msg'] = $ret['msg'];
            }
        }else{
            $resp['msg'] = $ret['msg'];
        }
        
        
        return redirect()->route('web.eqbao.contract_cost',['order_id'=>$order_id]);
    }
    
    public function contract_cost(){
        $order_id = $this->request->get('order_id','');
        $data = [];
        $ret = http_web($this->api_url['order_show'], [$order_id])->send();
        
        if(isset($ret['data']['user_id']) && $ret['data']['user_id']){
            $data['order_code'] = $ret['data']['order_code'];
            $info = http_web($this->api_url['company_info'],[$ret['data']['user_id']])->send();
            if(isset($info['data']['data'])){
                $data['buyer_user_name'] = $info['data']['data']['name'];
                $data['buyer_user_phone'] = $info['data']['data']['phone'];
                $data['buyer_user_angent'] = isset($info['data']['data']['company']['angent']) ?$info['data']['data']['company']['angent']:"" ;
                $data['buyer_company_address'] = isset($info['data']['data']['company']['company_address']) ?$info['data']['data']['company']['company_address']:"" ;
                $data['buyer_company_name'] = isset($info['data']['data']['company']['company_name']) ?$info['data']['data']['company']['company_name']:"" ;
            }
        }
        
        $info = http_web($this->api_url['company_info'],[session('user_id')])->send();
        
        if(isset($info['data']['data'])){
            $data['seller_user_name'] = $info['data']['data']['name'];
            $data['seller_user_phone'] = $info['data']['data']['phone'];
            $data['seller_user_angent'] = isset($info['data']['data']['company']['angent']) ?$info['data']['data']['company']['angent']:"" ;
            $data['seller_company_address'] = isset($info['data']['data']['company']['company_address']) ?$info['data']['data']['company']['company_address']:"" ;
            $data['seller_company_name'] = isset($info['data']['data']['company']['company_name']) ?$info['data']['data']['company']['company_name']:"" ;
        }
        
        old_set($data);
         
        return view('web.user.seller.contract_cost',$data);
    }
    
    /**
     * 新建模版印章
     */
    public function addTemplateSeal()
    {
        $resp = ['status'=>0,'msg'=>""];
        $params = $this->request->all(['templateType', 'color', 'hText', 'qText']);
        $result = http_web($this->api_url['find_by_userid'])->send();
        $id = 0;
        if(isset($result['data']['0']['account_id'])){
            $params['accountId'] = $result['data']['0']['account_id'];
            $id = $result['data']['0']['id'];
        }else{
            $resp['msg'] = "accountId错误";
            $this->response($resp);
        }
      
        $ret = $this->sign->addTemplateSeal(
            $params['accountId'],
            $params['templateType'],
            $params['color'],
            $params['hText'],
            $params['qText']
            );
        
        if(isset($ret['imageBase64'])){
            $data['yz_data'] = $ret['imageBase64'];
            $info = http_web($this->api_url['update'],[$id])->send($data);
            if(isset($info['code']) && $info['code'] == 0){
                $resp['status'] = 1;
                $resp['msg'] = $ret['msg'];
            }
        } 
        $this->response($resp);
    }
    
    /**
     * 添加手绘印章
     */
    public function addFileSeal()
    {
        $imgB64 = $this->request->post('sealData','');
        $imgB64 = substr($imgB64, strpos($imgB64, ',') + 1);
        $ret['errCode'] = 0;
        $ret['sealData'] = $imgB64;
        $this->response($ret);
    }
    
    /**
     * 平台用户签署
     */
    public function userSignPDF()
    {
        $resp = ['status'=>0,'msg'=>""];
        $user_type = $this->request->get("user_type",1);//1seller 2 buyer
        $order_id = $this->request->get("order_id","");
        
        if(!$order_id){
            $resp['msg'] = '订单号错误';
            $this->response($resp);
        }
        
        $result = http_web($this->api_url['find_by_userid'])->send();
        
        $accountId = "";
        $sealData = "";
        if(isset($result['data']['0']['account_id'])){
            $accountId = $result['data'][0]['account_id'];
            $sealData = $result['data'][0]['yz_data'];
            
            if(!$sealData){
                $resp['msg'] = "请先创建印章";
                $this->response($resp);
            }
        }else{
            $resp['msg'] = "请先创建账户";
            $this->response($resp);
        }
        
        
        $file_url = $this->request->get("file_url","");
        $id = 0;
        
        $result = http_web($this->api_url['find_by_orderid'],[$order_id])->send();
        if(isset($result['data'][0]['id'])){
            if($user_type == 1){
                $resp['msg'] = '卖家已签署合同';
                $this->response($resp);
            }
            $id = $result['data'][0]['id'];
            if($result['data'][0]['file_url'] ){
                $file_url=$result['data'][0]['file_url'];
            }
            
            if($result['data'][0]['status'] == 1){
                $resp['msg'] = '买家已签署合同';
                $this->response($resp);
            }
        }else{
            if($user_type == 2){
                $resp['msg'] = '卖家还未签署合同';
                $this->response($resp);
            }
        }
        
        if(!$file_url){
            $resp['msg'] = '待签署文件不能为空';
            $this->response($resp);
        }
 
        $srcPdfFile=public_path($file_url) ; 
        $filename = pathinfo($srcPdfFile,PATHINFO_FILENAME);
        $dist_filename = "";
        if($filename){
            $dist_filename = 'uploads/'.$filename.'_dist.pdf';
            $dstPdfFile=public_path($dist_filename);
        }
        
        
     
        $signType = $this->request->post('signType','');
        $isQrcodeSign = $this->request->post('isQrcodeSign','');
        $signPos = array(
            'posPage' =>  -1,//$this->request->post('posPage',1),
            'posX' =>  $this->request->post('posX'),
            'posY' =>  $this->request->post('posY'),
            'key' =>   $this->request->post('key'),
            'width' => 0,
            'isQrcodeSign'  =>  false,
            'addSignTime'=>true,
        );
        $signFile = array(
            'srcPdfFile' => $srcPdfFile, 
            'dstPdfFile' => $dstPdfFile, 
            'fileName' =>  '',
            'ownerPassword' => ''
        );
        
        $ret = $this->sign->userSignPDF($accountId, $signFile, $signPos, $signType, $sealData, $stream = true);
         
        if(isset($ret['signServiceId'])){
            $data['file_url'] = $dist_filename;
            $data['web_url'] = asset($dist_filename);
       
            if($user_type == 1){
                $data['order_id'] = $order_id;
                $data['seller_user_id'] = session('user_id');
                $data['seller_sign_id'] = $ret['signServiceId'];
                $data['status'] = 0;
                $info = http_web($this->api_url['contract_store'])->send($data);
            }
            
            if($user_type == 2){
                $data['buyer_user_id'] = session('user_id');
                $data['buyer_sign_id'] = $ret['signServiceId'];
                $data['status'] = 1;
                $info = http_web($this->api_url['contract_update'],[$id])->send($data);
            }
           
            if(isset($info['code']) && $info['code'] == 0){
                $resp['status'] = 1;
                $resp['msg'] = $ret['msg'];
            }
        }else{
            $resp['msg'] = $ret['msg'];
        }
        
        $this->response($resp);
    }
    
    /**
     * 平台自身签署
     */
    public function selfSignPDF()
    {
        
        $sealId = $this->request->post('sealId','');
        $signType = $this->request->post('signType','');
        $isQrcodeSign = $this->request->post('isQrcodeSign','');
        $signPos = array(
            'posPage' => -1,// $this->request->post('posPage'),
            'posX' =>  $this->request->post('posX'),
            'posY' =>  $this->request->post('posY'),
            'key' =>   $this->request->post('key'),
            'width' => 0,
            'isQrcodeSign'  => $isQrcodeSign == "false" ? false : true,
            'addSignTime'=>true,
        );
        $signFile = array(
            'srcPdfFile' => $this->request->post('srcFile'),
            'dstPdfFile' =>  str_replace("dist", "final", $this->request->post('srcFile')),// $this->request->post('srcFile'),
            'fileName' => $this->request->post('fileName'),
            'ownerPassword' => ''
        );
        $ret = $this->sign->selfSignPDF($signFile, $signPos, $sealId, $signType, $stream = true);
        $this->response($ret);
    }
    
    /**
     * 文档保全
     */
    public function saveSignedFile()
    {
        
        $docFilePath = $this->request->post('docFilePath');
        $docName = $this->request->post('docFilePath');
        $signServiceId =  $this->request->post('signServiceId');
        $saveRet = $this->sign->saveSignedFile($docFilePath, $docName, $signServiceId, $storeType = \tech\constants\StoreType::ESIGN_STORE);
        $this->response($saveRet);
    }
    
    private function response($data){
        echo Util::jsonEncode($data);
        exit();
    }
    
}